<?php

namespace App\Http\Service;

use App\Http\Util\Export;
use App\Http\Util\Result;
use App\Model\HouseCard;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

trait ServiceHouseCard{

    /**
     * czs
     * @return mixed
     * 虚拟卡号列表
     */
    public static function getList($id,$status,$limit){
        $model = DB::table('house_cards as a')->where("a.house_id",$id);
        if(!empty($status)) {
            $model->where('a.status',$status);
        }
        $list = $model
            ->leftJoin('members as b','b.id','=','a.member_id')
            ->select('a.*','b.account')
            ->orderBy('a.id','desc')
            ->paginate($limit);
        return Result::success()->setData($list);
    }

    /**
     * 导出
     * czs
     */
    public static function excel($status) {
        $model = DB::table('house_cards');
        if(!empty($status)) {
            $model->where('status',$status);
        }
        $arr[] = ["序号","卡号信息","状态"];
        $res = $model->select('content','status')->get();
        foreach ($res as $k=>$v) {
            $change = [1=>"未售出",2=>"已售出"];
            $arr[] = [$k+1,$v->content,$change[$v->status]];
        }
        $name = iconv('UTF-8', 'GBK', '虚拟商品信息');
        Export::excel($name,$arr);
    }

    /**
     * 导入
     * czs
     */
    public static function import($id) {
        $filePath = 'public/uploads/pic/else/'.iconv('UTF-8', 'GBK', 'excel').'.xls';
        Excel::load($filePath, function($reader) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
            foreach ($res as $k=>$v) {
                if ($k==0) {
                    continue;
                }
                $sel = DB::table('house_cards')->where('content',$v[1]);
                if ($sel->count()) {
                    continue;
                }
                $data['content'] = $v[1];
                $data['status'] = $v[2];
                DB::table('house_cards')->insert($data);
            }
        });
        $end = DB::table('house_cards')->where('house_id',NULL)->update(['house_id'=>$id]);
        if ($end) {
            return Result::success();
        }
    }
}


